package com.cyf.app.service.impl;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import com.cyf.app.service.JpushMessageService;
import com.cyf.util.JPushUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 极光推送
 * Created by cage on 2017/2/28.
 */
@Service
public class JpushMessageServiceImpl implements JpushMessageService {

    private static final String APP_KEY = "ee89e209b0c56ef438b5597a";
    private static final String MASTER_SECRET = "28d45f77772dc6905c4f3863";

    /**
     * 保存离线的时长。秒为单位。最多支持10天（864000秒）。 0 表示该消息不保存离线。即：用户在线马上发出，当前不在线用户将不会收到此消息。
     * 此参数不设置则表示默认，默认为保存3分钟的离线消息
     */
    private static final long MAX_RETRY_TIMES = 60 * 3;

    private static final Logger logger = LoggerFactory.getLogger(JpushMessageServiceImpl.class);

    @Override
    public void sendPushByAlias(String alias, String msgContent, Map<String, String> extras) {
//        ClientConfig clientConfig = ClientConfig.getInstance();
//        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
//        final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
//                null, clientConfig);
//        try {
//            String url = host + clientConfig.get(ClientConfig.PUSH_PATH);
//            PushPayload payload = JPushUtil.buildPushObject_all_all_Alias(alias,msgContent, extras);
//            ResponseWrapper responseWrapper = client.sendPost(url, payload.toString());
//
//            if (null != responseWrapper) {
//                loggerger.info("jpush发送结果：{}" , responseWrapper.responseContent);
//            }
//        } catch (APIConnectionException | APIRequestException e) {
//            e.printStackTrace();
//        } finally {
//            client.close();
//        }


        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
        // Call setHttpClient to set httpClient,
        // If you don't invoke this method, default httpClient will use NativeHttpClient.
//        ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
//        jpushClient.getPushClient().setHttpClient(httpClient);
        PushPayload payload = JPushUtil.buildPushObject_all_all_Alias(alias,msgContent, extras);
//        // For push, all you need do is to build PushPayload object.
//        PushPayload payload = buildPushObject_all_alias_alert();
        try {
            PushResult result = jpushClient.sendPush(payload);
            logger.info("jpush发送结果：{} ", result);
            // 如果使用 NettyHttpClient，需要手动调用 close 方法退出进程
            // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
            // jpushClient.close();
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
            logger.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
            logger.info("Msg ID: " + e.getMsgId());
            logger.error("Sendno: " + payload.getSendno());
        }
    }
}
